package Thread;


import java.util.concurrent.PriorityBlockingQueue;


/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2023-02-26
 * Time: 9:45
 */
class MyTask implements Comparable<MyTask>{
    //要执行的任务
    private Runnable runnable;
    //任务在啥时候执行(使用毫秒时间戳执行)
    private long time;
    public MyTask(Runnable runnable,long time){
        this.runnable = runnable;
        this.time = time;
    }
    public long getTime(){
        return time;
    }
    //执行任务
    public void  run(){
        runnable.run();
    }

    @Override
    public int compareTo(MyTask o) {
        return (int) (this.time - o.time);
    }
}
//简单的定时器
class MyTimer{
    //扫描线程
    private Thread t = null;
    //有一个阻塞优先级队列,来保存任务
    private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();
    //专门使用对象进行加锁/等待通知
    private Object locker = new Object();
    public MyTimer(){
        t = new Thread(){
            public void run(){
                while (true) {
                    try {
                        //取出队首元素,检查队首元素任务是否到时间
                        //时间没到,就把任务塞回队列
                        //时间到了,就把任务进行执行
                        System.out.println("this2: "+this);
                        synchronized (locker) {
                            MyTask myTask =  queue.take();
                            long curtime = System.currentTimeMillis();
                            if(curtime < myTask.getTime()){
                                queue.put(myTask);
                                //在put之后,进行一个wait
                                locker.wait(myTask.getTime() - curtime);
                            }else {
                                myTask.run();
                            }
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        };
        t.start();
    }
    //指定两个参数(任务内容,任务在多少毫秒之后执行)
    public void schedule(Runnable runnable,long after){
        //时间的换算
        MyTask task = new MyTask(runnable,System.currentTimeMillis()+after);
        queue.put(task);
        System.out.println("this1: "+ this);
        synchronized (locker){
            locker.notify();
        }
    }

}
public class Thread26 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("任务1");
            }
        },2000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("任务2");
            }
        },1000);
    }

}
